package com.tedu.spring.boot.demo1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tedu.spring.boot.demo1.entity.dto.UserLoginDTO;
import com.tedu.spring.boot.demo1.entity.dto.UserRegDTO;
import com.tedu.spring.boot.demo1.entity.pojo.User;
import com.tedu.spring.boot.demo1.entity.vo.UserVO;
import com.tedu.spring.boot.demo1.mapper.UserMapper;
import com.tedu.spring.boot.demo1.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Author：毕龙
 * Date: 2024/8/27 16:33
 */
@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void insertUser(UserRegDTO userRegDTO) {
        //通过用户名查询用户是否存在
        String username = userRegDTO.getUsername();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> list = userMapper.selectList(queryWrapper);
        if(list.size()>0){
            throw new RuntimeException("用户已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        int i = userMapper.insert(user);
        if (i==0)
            throw new RuntimeException("添加数据失败");

    }

    @Override
    public UserVO selectUser(UserLoginDTO userLoginDTO) {
        //判断用户是否存在
        String username = userLoginDTO.getUsername();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //equals
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if(user == null)
            throw  new RuntimeException("用户名不存在");

        if (!user.getPassword().equals(userLoginDTO.getPassword()))
            throw  new RuntimeException("密码错误");
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user,vo);
        return vo;
    }
}
